// Package udp.
// creator 2022-02-25 02:15:16
// Author  zhenxinma.
package udp

import (
	"context"
	"crypto/tls"
	"fmt"
	"github.com/lucas-clemente/quic-go"
	"io"
)

type Client struct {
	Addr    string
	Session quic.Session
}

func NewClient(addr string) *Client {

	session, err := quic.DialAddr(addr,
		&tls.Config{
			InsecureSkipVerify: true,
			NextProtos:         []string{"quic-echo-example"}},
		nil)
	if nil != err {
		panic(err)
	}

	client := &Client{
		Addr:    addr,
		Session: session,
	}
	return client
}

func (c *Client) SendMessage(data []byte) error {

	stream, err := c.Session.OpenStreamSync(context.Background())
	if err != nil {
		panic(err)
	}

	fmt.Println("开始发送数据.")
	_, err = stream.Write(data)
	if err != nil {
		panic(err)
	}

	fmt.Println("中间状态.")

	buf := make([]byte, len(data))
	_, err = io.ReadFull(stream, buf)
	if err != nil {
		panic(err.Error())
	}

	fmt.Println("end..")
	fmt.Println(string(buf))
	return nil
}
